﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

public partial class yzadmin_data_collect_mkzhan : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    private JObject result = new JObject();
    static CookieContainer cookies = new CookieContainer();
    string domain = "http://www.mkzhan.com";
    string baseUrl = "http://www.mkzhan.com/comic/clist/{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}.html";
    string searchUrl = "http://www.mkzhan.com/comic/so/{0}-{1}-{2}.html";
    string zm = "0";
    string tc = "0";
    string dz = "0";
    string lx = "0";
    string jd = "0";
    string zp = "2";
    string px = "2";
    int p = 1;
    private string getUrl()
    {
        return string.Format(baseUrl, new object[] { zm, tc, dz, lx, jd, zp, px, p });
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "import":
                    this.ProcessImport();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessImport()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            string[] urlArray = Request["zjurl"].Split('\n');
            //Array.Reverse(urlArray);//数组倒序
            foreach (string url in urlArray)
            {
                string[] arr = url.Split('|');
                List<string> zjlist = new List<string>(arr);
                zjlist.RemoveAt(0);
                for (int i = 0; i < zjlist.Count; i++)
                {
                    zjlist[i] = "http://www.mkzhan.com/Public/upload/comic" + zjlist[i];
                }
                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.cid = Convert.ToInt32(Request["id"]);
                zj.zjmc = arr[0];
                zj.time = DateTime.Now;
                zj.isdownload = false;
                zj.tpadd = Request["tpadd"] + zj.zjmc.Split(' ')[0] + "/";
                zj.tps = zjlist.Count;
                zj.tpurl = string.Join("|", zjlist.ToArray());
                YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
                if (urlArray.Length == 1 && !string.IsNullOrEmpty(Request["zjid"]))
                {
                    zj.id = int.Parse(Request["zjid"]);
                    zjbll.Update(zj);
                }
                else
                {
                    zjbll.Add(zj);
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    

    private void ProcessSingle()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(Request["url"]);
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class='introduction_left_3']");
            result.Add("mhmc", node.SelectSingleNode("div[2]/div[1]/h2/span[1]").InnerText);
            result.Add("mhfm", node.SelectSingleNode("div/div/div/img").Attributes["src"].Value);
            result.Add("zzmc", node.SelectSingleNode("div[2]/div[1]/h2/span[2]/a").InnerText);
            result.Add("score", node.SelectSingleNode("div[2]/div[3]/div[@class='score']").InnerText);
            result.Add("classname", node.SelectSingleNode("div[2]/ul/li[3]").InnerText.Split('：')[1].Trim());
            result.Add("tc", node.SelectSingleNode("div[2]/ul/li[4]").InnerText.Split('：')[1].Trim());
            result.Add("time", node.SelectSingleNode("div[2]/ul/li[5]").InnerText.Split('：')[1].Trim());
            result.Add("mhjj", node.SelectSingleNode("div[5]").InnerText.Trim());
            result.Add("mhjs", node.SelectSingleNode("div[5]").InnerHtml.Trim());
            JArray chapters = new JArray();

            HttpWebRequest myHttpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create("http://www.mkzhan.com/index.php/reader/show/");
            myHttpWebRequest.Method = "POST";
            myHttpWebRequest.Accept = "*/*";
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
            myHttpWebRequest.CookieContainer = new CookieContainer();
            myHttpWebRequest.CookieContainer.Add(new Uri(domain), new Cookie("TP_showType", "czoz0iJuZXci0w%3D%3D"));
            #region 填充要post的内容
            byte[] postBytes = Encoding.ASCII.GetBytes("id=" + doc.GetElementbyId("comicid").Attributes["value"].Value);
            myHttpWebRequest.ContentLength = postBytes.Length;
            System.IO.Stream requestStream = myHttpWebRequest.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();
            #endregion
            string stringResponse;
            using (System.IO.StreamReader responseReader = new System.IO.StreamReader(myHttpWebRequest.GetResponse().GetResponseStream()))
            {
                stringResponse = responseReader.ReadToEnd();
            }
            myHttpWebRequest.GetResponse().Close();

            JArray ar = JArray.Parse(stringResponse);
            foreach (JToken item in ar)
            {
                JObject chapter = new JObject();
                chapter.Add("zjmc", item["name"]);
                chapter.Add("zjurl", item["name"] + "|" + item["comicimg"]);
                chapters.Add(chapter);
            }
            result.Add("chapters", chapters);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        try
        {
            if (!string.IsNullOrEmpty(Request["zm"]))
            {
                zm = Request["zm"];
            }
            if (!string.IsNullOrEmpty(Request["tc"]))
            {
                tc = Request["tc"];
            }
            if (!string.IsNullOrEmpty(Request["dz"]))
            {
                dz = Request["dz"];
            }
            if (!string.IsNullOrEmpty(Request["lx"]))
            {
                lx = Request["lx"];
            }
            if (!string.IsNullOrEmpty(Request["jd"]))
            {
                jd = Request["jd"];
            }
            if (!string.IsNullOrEmpty(Request["zp"]))
            {
                zp = Request["zp"];
            }
            if (!string.IsNullOrEmpty(Request["px"]))
            {
                px = Request["px"];
            }
            p = Convert.ToInt32(Request["page"]);
            HtmlWeb webClient = this.getWebClient();
            JArray data = new JArray();
            HtmlDocument doc;
            if (string.IsNullOrEmpty(Request["query"]))
            {
                doc = webClient.Load(this.getUrl());
            }else
            {
                doc = webClient.Load(string.Format(searchUrl, new object[] { Request["query"].Trim(), px, p }));
	        }
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//ul[@class='liebiao_tu']/li");
            foreach (HtmlNode node in nodes)
            {
                JObject jo = new JObject();
                jo.Add("mhmc", node.SelectSingleNode("a/h2").InnerText);
                jo.Add("mhurl", domain + node.SelectSingleNode("a").Attributes["href"].Value);
                jo.Add("zzmc", node.SelectSingleNode("p[1]").InnerText.Split('：')[1]);
                string score = node.SelectSingleNode("p[2]/span[1]").InnerText;
                if (node.SelectSingleNode("p[2]/span[2]") != null)
                {
                    score += node.SelectSingleNode("p[2]/span[2]").InnerText;
                }
                jo.Add("score", score);
                data.Add(jo);
            }
            result.Add("data", data);
            result.Add("total", YuuzleComic.Common.Input.GetNumberInt(doc.DocumentNode.SelectSingleNode("//span[@class='page_info']").InnerText));
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }

    }

    private HtmlWeb getWebClient()
    {
        HtmlWeb webClient = new HtmlWeb();
        HtmlAgilityPack.HtmlWeb.PreRequestHandler handler = delegate(HttpWebRequest request)
        {
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.CookieContainer = cookies;
            request.Timeout = 500000;
            return true;
        };
        webClient.PreRequest += handler;
        return webClient;
    }
}